package wghlpay

import (
    "fmt"
	"time"
	"errors"
	"thirdpaysdk/core"
	"thirdpaysdk/utils/signature"
	//"github.com/astaxie/beego"
)

type SdkParamsInfo struct {
	TimeStamp string `json:"timeStamp"`
	Package   string `json:"package"`
	PaySign   string `json:"paySign"`
	AppId     string `json:"appId"`
	SignType  string `json:"signType"`
	NonceStr  string `json:"nonceStr"`
}

type MicroAppPayResponse struct {
	ReturnCode     string `json:"return_code"`
	ReturnMsg      string `json:"return_msg,omitempty"`
	ResultCode     string `json:"result_code"`
	PartnerOrderId string `json:"partner_order_id"`
	FullName       string `json:"full_name"`
	PartnerName    string `json:"partner_name"`
	Channel        string `json:"channel"`
	PartnerCode    string `json:"partner_code"`
	OrderId        string `json:"order_id"`
	SdkParams      *SdkParamsInfo `json:"sdk_params,omitempty"`
}

/*
{"partner_order_id":"912356789767123","full_name":"E & K TRADE PTY LTD","partner_name":"ALL 4 KIDS","channel":"Wechat","sdk_params":{"timeStamp":"1531827286","package":"prepay_id=wx17193210753585bacfbe15461543938668","paySign":"B7AC15446AB884130D2695F3E7285FA1","appId":"wx70285e9cb48580ec","signType":"MD5","nonceStr":"fCCwfkrdGC0Usl2cTX9KKgI61FeucD"},"result_code":"EXISTS","partner_code":"EKTD","order_id":"EKTD-20180717213210463-00FZX3WUC","return_code":"SUCCESS"}
*/

func  MicroAppPay(partnerCode,orderId,credentialCode,des,currency,notifyUrl,operator,
                  appid,customerId string,price int)(rsp *MicroAppPayResponse, err error){
	incompleteURL := "https://mpay.royalpay.com.au/api/v1.0/gateway/partners/%s/microapp_orders/%s?time=%d&nonce_str=%s&sign=%s"
	
	rsp = &MicroAppPayResponse{}
	request := struct {
		Description string `json:"description"`
		Price       int    `json:"price"`
		Currency    string `json:"currency"`
		NotifyUrl   string `json:"notify_url"`
		Operator    string `json:"operator"`
		AppId       string `json:"appid"`
		CustomerId  string `json:"customer_id"`
	}{
		Description: des,
		Price:       price,
		Currency:    currency,
		NotifyUrl:   notifyUrl,
		Operator:    operator,
		AppId:       appid,
		CustomerId:  customerId,
	}
	curTime := time.Now().Unix()*1000
	nonceStr := signature.GetNonceStr(20)
	sign := signature.MakeSha256Sign(partnerCode,curTime,nonceStr,credentialCode)
	serverUrl := fmt.Sprintf(incompleteURL, partnerCode, orderId, curTime, nonceStr, sign)
	//
	client := core.GetPayJSONClient("PUT", serverUrl)
	tbdata, e := client.PayJsonExcute(request, rsp)
    if e != nil {
		err = e
		return
	}
	if rsp.ReturnCode != "SUCCESS" {
		err = errors.New(string(tbdata))
        return
	}
	//beego.Debug("tbdata:", string(tbdata))
	return
}
